<?php


namespace app\api\controller\v1;

use app\api\model\UserAddress as UserAddressModel;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\AddressValidate;
use app\common\exception\AddressException;
use app\common\message\SuccessMessage;

class Address extends Base
{
    protected $beforeActionList = [
        //user和admin都能访问
        'checkPrimaryScope' => ['only' => 'create,getOne,update']
    ];

    /**
     * 根据token来获取uid
     * 根据uid查找用户数据，判断用户是否存在，不存在抛出异常
     * 获取用户从客户端传过来的地址信息
     * 根据地址信息判断，是添加还是更新
     */
    public function create()
    {
        $validate = new AddressValidate();
        $validate->goCheck();
        $user = $this->getCurrentUser();
        $userAddress = $validate->getDataByRule(input('post./a'));
        $user->address()->save($userAddress);
        return new SuccessMessage([]);
    }

    // 获取用户地址信息
    public function getOne()
    {
        (new IDMustBePositiveInt())->goCheck();
        $id = $this->request->param('id');
        $user = $this->getCurrentUser();
        $address = UserAddressModel::getOne($user->id, $id);
        if(empty($address)) {
            throw new AddressException();
        }
        return $address;
    }
    // 修改用户地址信息
    public function update()
    {
        (new IDMustBePositiveInt())->goCheck();
        $address_id = input('post.id/d');
        $validate = new AddressValidate();
        $validate->goCheck();
        $userAddress = $validate->getDataByRule(input('post./a'));
        $user = $this->getCurrentUser();
        UserAddressModel::updateOne($user->id, $address_id, $userAddress);
        return new SuccessMessage();
    }
}